package com.supor.aiot.home.ui.device.config;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Handler;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.LinearLayout;

import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.SystemUtils;
import com.android.baseconfig.common.utils.ThreadUtils;
import com.android.baseconfig.common.utils.ToastUtils;
import com.android.baseconfig.common.views.CenterImageSpan;
import com.supor.aiot.common.app.AppAgent;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.base.BaseConfigActivity;
import com.supor.aiot.common.base.NoViewModel;
import com.supor.aiot.common.entity.ProductType;
import com.supor.aiot.common.helper.ActivityHelper;
import com.supor.aiot.common.helper.MediaManager;
import com.supor.aiot.common.helper.WifiStationManager;
import com.supor.aiot.home.R;
import com.supor.aiot.home.databinding.ActivitySelectWifiBinding;
import com.supor.aiot.home.helper.WlanDescriptionSpan;

import java.util.concurrent.atomic.AtomicBoolean;

import androidx.core.content.res.ResourcesCompat;

import static com.supor.aiot.common.app.Constants.SETTING_GPS;

/**
 * ---------------------------------------------------------------- <br>
 * Copyright (C) 2014-2020, by het, Shenzhen, All rights reserved.  <br>
 * ---------------------------------------------------------------- <br>
 * <p>
 * 描述: SelectWifiActivity <br>
 * 作者: lei <br>
 * 日期: 2020/12/13 <br>
 */
public class SelectWifiActivity extends BaseConfigActivity<NoViewModel, ActivitySelectWifiBinding> {
    Handler handler;
    AtomicBoolean ifFristResumed = new AtomicBoolean(true);
    AtomicBoolean ifJumpSettings = new AtomicBoolean(false);
    private String deviceBrand = Build.BRAND;//手机品牌
    private String devicemodel = Build.MODEL;//手机型号
    private String wlanTips;
    private ProductType.ProductModel productModel;

    @Override
    protected int resourceId() {
        return R.layout.activity_select_wifi;
    }

    public void initView() {
        super.initView();
        Intent intent = getIntent();
        if (intent != null) {
            productModel = (ProductType.ProductModel) intent.getSerializableExtra(Constants.Key.PRODUCT_MODEL);
            if (productModel == null) {
                Logc.d(TAG, "iotDevice is null");
                finish();
            }
        }
        bindingView.setViewM(this);
        bindingView.toolbar.setIvLeftOnClickListener(v -> finish());
        bindingView.toolbar.setTvLeftOnClickListener(v -> finish());
        wlanTips = getString(R.string.bind_select_wifi_step3_1);
        setstep3();

        Logc.i("============ 手机型号" + deviceBrand);

        LinearLayout.LayoutParams selectWifiLayoutParams =
                (LinearLayout.LayoutParams) bindingView.llSelectWifi.getLayoutParams();
        LinearLayout.LayoutParams selectWifiTipLayoutParams =
                (LinearLayout.LayoutParams) bindingView.llSelectWifiTip.getLayoutParams();
        // LinearLayout.LayoutParams btnNoFoundWifiLayoutParams =
        //         (LinearLayout.LayoutParams) bindingView.btnNoFoundWifi.getLayoutParams();
        if (AppAgent.smallScreen) {
            selectWifiLayoutParams.topMargin = getResources().getDimensionPixelSize(R.dimen.dp_8);
            selectWifiTipLayoutParams.topMargin =
                    getResources().getDimensionPixelSize(R.dimen.dp_8);
            // btnNoFoundWifiLayoutParams.bottomMargin =
            //         getResources().getDimensionPixelSize(R.dimen.dp_14);
        } else {
            selectWifiLayoutParams.topMargin = getResources().getDimensionPixelSize(R.dimen.dp_17);
            selectWifiTipLayoutParams.topMargin =
                    getResources().getDimensionPixelSize(R.dimen.dp_17);
            // btnNoFoundWifiLayoutParams.bottomMargin =
            //         getResources().getDimensionPixelSize(R.dimen.dp_24);
        }
        bindingView.llSelectWifi.setLayoutParams(selectWifiLayoutParams);
        bindingView.llSelectWifiTip.setLayoutParams(selectWifiTipLayoutParams);
        // bindingView.btnNoFoundWifi.setLayoutParams(btnNoFoundWifiLayoutParams);


        if (Constants.Type.TYPE_CHEF_MACHINE.equalsIgnoreCase(productModel.modelTypeId)) {
            bindingView.ivWifiGuide.setImageResource(R.mipmap.ic_select_wifi);
            bindingView.tvStep12.setText(R.string.bind_select_wifi_step1_1);
        } else if (Constants.Type.TYPE_OVEN.equalsIgnoreCase(productModel.modelTypeId)) {
            bindingView.ivWifiGuide.setImageResource(R.mipmap.ic_select_wifi_oven);
            bindingView.tvStep12.setText(R.string.bind_select_wifi_oven_step1_1);
        } else if (Constants.Type.TYPE_RICE_COOKER.equalsIgnoreCase(productModel.modelTypeId)) {
            bindingView.ivWifiGuide.setImageResource(R.mipmap.ic_select_wifi_rice_cooker);
            bindingView.tvStep12.setText(R.string.bind_select_wifi_rice_cooker_step1_1);
        } else if (Constants.Type.TYPE_WATER_PURIFIER.equalsIgnoreCase(productModel.modelTypeId)) {
            bindingView.ivWifiGuide.setImageResource(R.mipmap.ic_select_wifi_water_purifier);
            bindingView.tvStep12.setText(R.string.bind_select_wifi_water_purifier_step1_1);
        }

        // Intent intent = getIntent();
        // if (intent != null) {
        //     int type = intent.getIntExtra(Constants.Key.param_type, 0);
        //     if (type == APHelper.Step.NO_FOUND_AP.ordinal()) {
        //         bindingView.btnNoFoundWifi.setVisibility(View.GONE);
        //     }
        // }
        handler = new Handler();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!ifFristResumed.get()) {
            if (!ifJumpSettings.get()) {
                return;
            }
            checkNet();
            ifJumpSettings.set(false);
        } else {
            ifFristResumed.set(false);
        }
    }

    @Override
    public void updateNetStatus(int type) {
        Logc.i("connect type: " + type);
        if (type == 1) {
            // checkNet();
        }
    }

    private synchronized void checkNet() {
        String currentWifiSSID = WifiStationManager.getInstance().getCurrentWifiSSID();
        Logc.i("current SSID: " + currentWifiSSID + ", build: " + Build.VERSION.RELEASE);
        if (currentWifiSSID != null && currentWifiSSID.startsWith(Constants.SUPOR_AP_PREFIX)) {
            if (Constants.USE_VOICE) {
                ThreadUtils.execute(() -> MediaManager.getInstance().voiceTip("voice2.mp3"));
            }
            // 0返回到配网页面
            Intent intent = new Intent(this, WifiConfigActivity.class);
            if (getIntent() != null && getIntent().getExtras() != null) {
                intent.putExtras(getIntent().getExtras());
            }
            intent.putExtra(Constants.Key.PRODUCT_MODEL, productModel);
            startActivityForResult(intent, Constants.REQUEST_CODE);
        } else {
            // bindingView.btnNoFoundWifi.setVisibility(View.GONE);
            bindingView.btnNextStep.setText(R.string.retry);
            if (Constants.USE_VOICE) {
                ThreadUtils.execute(() -> MediaManager.getInstance().voiceTip("voice3.mp3"));
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // Logc.i("onActivityResult: requestCode= " + requestCode);
        if (SETTING_GPS == requestCode) {
            if (!SystemUtils.isGpsEnabled(this)) {
                ToastUtils.getInstance().showCustomToast(getResources().getString(R.string.bind_open_loc_faild));
            } else {
                Logc.i("============ 打开定位成功");
            }
        } else if (Constants.REQUEST_CODE == requestCode) {
            if (resultCode == 1) {
                setResult(1);
                finish();
            }
        }
    }

    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.btn_next_step) {
            if (getString(R.string.retry).equalsIgnoreCase(bindingView.btnNextStep.getText().toString())) {
                // 1返回到网络引导页面
                setResult(1);
                finish();
                return;
            }
            ActivityHelper.gotoWiFiSetting(this);
            if (Constants.USE_VOICE) {
                ThreadUtils.execute(() -> MediaManager.getInstance().voiceTip("voice1.mp3"), 100);
            }
            ifJumpSettings.set(true);
        } else if (id == R.id.btn_no_found_wifi) {// 1返回到网络引导页面
            // setResult(1);
            finish();
        } else if (id == R.id.tv_step2_2_copy) {
            ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            // 创建普通字符型ClipData
            ClipData mClipData = ClipData.newPlainText("Label",
                    getString(R.string.bind_select_wifi_step1_2));
            // 将ClipData内容放到系统剪贴板里。
            cm.setPrimaryClip(mClipData);
            ToastUtils.getInstance().showCustomToast(this, getString(R.string.already_copy));
        }
    }

    //小米，华为，oppo，vivo有wlan+功能的手机品牌
    public void setstep3() {
        switch (deviceBrand) {
            case "HUAWEI":
            case "HONOR":
                setStep3Description(getString(R.string.wlan_1));
                break;
            case "vivo":
                setStep3Description(getString(R.string.wlan_3));
                break;
            case "OPPO":
                setStep3Description(getString(R.string.wlan_2));
                break;
            case "Xiaomi":
                setStep3Description(getString(R.string.wlan_2));
                break;
            default:
                bindingView.tvStep3.setVisibility(View.INVISIBLE);
                break;
        }
    }

    public void setStep3Description(String wlan) {
        String step3 = String.format(wlanTips, wlan);
        String closeWay = getString(R.string.close_way);
        SpannableString span = new SpannableString(step3);
        int start = step3.indexOf(closeWay);
        int end = step3.indexOf(closeWay) + closeWay.length();
        span.setSpan(new WlanDescriptionSpan(getString(R.string.close_way), deviceBrand,
                SelectWifiActivity.this), start, end + 2, SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
        // span.setSpan(new UnderlineSpan(), start, end, SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
        span.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)), start,
                end, SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
        //拿到所加图片的drawable对象
        Drawable drawable = ResourcesCompat.getDrawable(getResources(), R.mipmap.ic_close_way,
                null);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        CenterImageSpan imageSpan = new CenterImageSpan(drawable);
        span.setSpan(imageSpan, end + 1, end + 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        bindingView.tvStep3.setText(span);
        bindingView.tvStep3.setMovementMethod(LinkMovementMethod.getInstance());
    }

}
